package com.crimsec.utils.dinfo;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;


/**
 * $Id$
 */
public class Utils implements IDefaults {

    private Properties props = new Properties();
    private Map<String, String> defaults = new HashMap<String, String>();

    /**
     * @param other propeties for search namespace
     * @param namespace name (don't use wildchars)
     * @return a new Properties with keys(an their values) who names start with
     * given namesapace
     */
    public static Properties getPropertiesForNamespace(String namespace, Properties other) {
        if (other != null) {
            Properties result = new Properties();
            Set<String> keys = other.stringPropertyNames();
            for (String key : keys) {
                if (key.startsWith(namespace)) {
                    result.put(key, other.getProperty(key));
                }
            }
            return result;
        } else {
            return null;
        }
    }

    public Utils(String name) throws IOException {
        loadProps(name);
    }

    public Utils() throws IOException {
        loadFromResources(PROPSNAME);
    }

    private void loadProps(String name) throws IOException {
        try {
            loadFromURL(name);
        } catch (IOException e) {
            loadFromResources(PROPSNAME);
        }
    }

    private void constructDefauls() {
        
    }

    private void loadFromURL(String file) throws IOException {
        URL url = new URL(file);
        props.load(new InputStreamReader(url.openStream()));
    }

    private void loadFromResources(String resName) throws IOException {
        //TODO: разобраться с заргузкой ресурсов при любых обстоятельствах, может подсмотреть в log4j сырцах
        InputStream i = Class.class.getResourceAsStream("/" + resName);
        InputStreamReader ir = new InputStreamReader(i);
        props.load(ir);
    }



    public String getValue(String propName) {
        String candidate = props.getProperty(propName);
        if ((candidate == null) || (candidate.isEmpty())) {
            candidate = defaults.get(propName);
        }
        return candidate;
    } 

}
